import dayjs from "dayjs";
import Form from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "@/utils/viewsPublic";
import { renderOption } from "@/utils/viewsRender";
import { transformI18n } from "@/plugins/i18n";
import { getKeyList } from "@pureadmin/utils";
import { roleApi } from "@/api/organization/role";
import { getMenuList } from "@/api/system/menu";
import { type Ref, reactive, ref, onMounted, watch, shallowRef } from "vue";
import { hasAuth } from "@/router/utils";
import { useI18n } from "vue-i18n";

export function useRole(tableRef: Ref, treeRef: Ref) {
  const { t } = useI18n();
  const switchLoadMap = ref({});
  const isShow = ref(false);
  const curRow = ref();
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const treeData = ref([]);
  const treeIds = ref([]);
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };

  const { switchStyle } = usePublicHooks();

  const api = reactive({
    list: roleApi.list,
    fields: roleApi.fields,
    save: roleApi.save,
    delete: roleApi.delete
  });
  const auth = reactive({
    list: true,
    create: hasAuth("add"),
    update: hasAuth("edit"),
    delete: hasAuth("delete"),
    batchDelete: hasAuth("delete"),
    import: hasAuth("import"),
    export: hasAuth("export"),
    download: hasAuth("download"),
    auth: hasAuth("auth")
  });

  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "id"
    },
    {
      label: "角色名称",
      prop: "name"
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 160
    },
    {
      label: "创建时间",
      prop: "create_time",
      minWidth: 160,
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  const editForm = shallowRef({
    title: t("role.title"),
    form: Form,
    props: {
      treeMenuData: row => {
        return {
          treeData: treeData.value,
          treeIds: treeIds.value,
          treeSelected: row?.menu_ids ?? []
        };
      }
    },
    row: {
      status: row => {
        return row.status ?? 1;
      },
      menu_ids: row => {
        return row.menu_ids ?? [];
      }
    },
    columns: () => {
      return [
        {
          prop: "name",
          valueType: "input"
        },
        {
          prop: "code",
          valueType: "input"
        },
        {
          prop: "status",
          valueType: "radio",
          renderField: renderOption()
        },
        {
          prop: "remark",
          valueType: "textarea"
        },
        {
          prop: "menu_ids",
          valueType: "input"
        }
      ];
    }
  });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        if (!hasAuth("edit")) {
          message("权限不足！", { type: "error" });
          return false;
        }
        api.save({ id: row.id, status: row.status }).then(res => {
          if (res.code == 200) {
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: true
              }
            );
            setTimeout(() => {
              switchLoadMap.value[index] = Object.assign(
                {},
                switchLoadMap.value[index],
                {
                  loading: false
                }
              );
              message(`已${row.status === 0 ? "停用" : "启用"}${row.name}`, {
                type: "success"
              });
            }, 300);
          } else {
            message(res.error, { type: "error" });
          }
        });
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  /** 菜单权限 */
  async function handleMenu(row?: any) {
    const { id, menu_ids } = row;
    if (id) {
      curRow.value = row;
      isShow.value = true;
      //延迟加载
      setTimeout(() => {
        treeRef.value.setCheckedKeys(JSON.parse(JSON.stringify(menu_ids)));
      }, 50);
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { id, name } = curRow.value;
    // 根据用户 id 调用实际项目中菜单权限修改接口
    api.save({ id: id, menu_ids: treeRef.value.getCheckedKeys() }).then(res => {
      console.log(res);
      message(`角色名称为${name}的菜单权限修改成功`, {
        type: "success"
      });
      tableRef.value.onSearch(); // 刷新表格数据
    });
  }

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    const { data } = await getMenuList({ page_type: 0 });
    treeIds.value = getKeyList(data.list, "id");
    treeData.value = handleTree(data.list);
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    api,
    auth,
    columns,
    isShow,
    curRow,
    isExpandAll,
    isSelectAll,
    isLinkage,
    handleMenu,
    handleSave,
    treeSearchValue,
    onQueryChanged,
    treeData,
    treeProps,
    filterMethod,
    transformI18n,
    editForm
  };
}
